import Message from 'tdesign-miniprogram/message/index';
import { novelAPI } from '~/api/novel';
import { interactionAPI } from '~/api/interaction';
const authUtils = require('~/utils/auth.js');

Page({
  data: {
    chapterId: '',
    novelId: '',
    chapterData: {},
    comments: [],
    commentContent: '',
    replyTarget: '',
    replyCommentId: '',
    commentsPagination: {
      page: 1,
      pageSize: 20,
      hasMore: true
    }
  },

  /**
   * 页面加载
   */
  onLoad(options) {
    console.log('章节详情页面加载参数:', options);
    const { chapterId, novelId } = options;
    if (!chapterId || !novelId) {
      console.error('参数错误:', { chapterId, novelId });
      Message.error({
        context: this,
        content: '参数错误'
      });
      wx.navigateBack();
      return;
    }

    this.setData({ chapterId, novelId });
    this.loadChapterData();
    this.loadComments();
  },

  /**
   * 返回上一页
   */
  onBack() {
    wx.navigateBack();
  },

  /**
   * 显示操作菜单
   */
  onShowActions() {
    wx.showActionSheet({
      itemList: ['举报', '分享'],
      success: (res) => {
        switch (res.tapIndex) {
          case 0:
            this.onReport();
            break;
          case 1:
            this.onShare();
            break;
        }
      }
    });
  },

  /**
   * 加载章节数据
   */
  async loadChapterData() {
    try {
      const { chapterId, novelId } = this.data;
      console.log('开始加载章节数据:', { chapterId, novelId });
      
      // 获取章节详情
      const response = await novelAPI.getChapterDetail(chapterId);
      console.log('章节详情API响应:', response);
      
      if (response.code === 200) {
        this.setData({
          chapterData: response.data
        });
        
        // 设置页面标题
        wx.setNavigationBarTitle({
          title: response.data.title || '章节详情'
        });
        
        console.log('章节数据加载成功:', response.data);
      } else {
        throw new Error(response.message || '加载章节失败');
      }
    } catch (error) {
      console.error('加载章节数据失败:', error);
      Message.error({
        context: this,
        content: error.message || '加载失败，请重试'
      });
    }
  },

  /**
   * 点赞
   */
  async onLike() {
    if (!authUtils.isLoggedIn()) {
      authUtils.redirectToLogin();
      return;
    }

    try {
      const { chapterId, chapterData } = this.data;
      
      if (chapterData.isLiked) {
        await interactionAPI.chapter.unlike(chapterId);
        this.setData({
          'chapterData.isLiked': false,
          'chapterData.likeCount': Math.max(0, (chapterData.likeCount || 0) - 1)
        });
        Message.success({
          context: this,
          content: '取消点赞'
        });
      } else {
        await interactionAPI.chapter.like(chapterId);
        this.setData({
          'chapterData.isLiked': true,
          'chapterData.likeCount': (chapterData.likeCount || 0) + 1
        });
        Message.success({
          context: this,
          content: '点赞成功'
        });
      }
    } catch (error) {
      console.error('点赞操作失败:', error);
      Message.error({
        context: this,
        content: error.message || '操作失败，请重试'
      });
    }
  },

  /**
   * 收藏
   */
  async onFavorite() {
    if (!authUtils.isLoggedIn()) {
      authUtils.redirectToLogin();
      return;
    }

    try {
      const { chapterId, chapterData } = this.data;
      
      if (chapterData.isFavorited) {
        await interactionAPI.unfavorite(interactionAPI.TARGET_TYPES.CHAPTER, chapterId);
        this.setData({
          'chapterData.isFavorited': false,
          'chapterData.favoriteCount': Math.max(0, (chapterData.favoriteCount || 0) - 1)
        });
        Message.success({
          context: this,
          content: '取消收藏'
        });
      } else {
        await interactionAPI.favorite(interactionAPI.TARGET_TYPES.CHAPTER, chapterId);
        this.setData({
          'chapterData.isFavorited': true,
          'chapterData.favoriteCount': (chapterData.favoriteCount || 0) + 1
        });
        Message.success({
          context: this,
          content: '收藏成功'
        });
      }
    } catch (error) {
      console.error('收藏操作失败:', error);
      Message.error({
        context: this,
        content: error.message || '操作失败，请重试'
      });
    }
  },

  /**
   * 分享
   */
  onShare() {
    Message.info({
      context: this,
      content: '分享功能开发中'
    });
  },

  /**
   * 举报
   */
  onReport() {
    Message.info({
      context: this,
      content: '举报功能开发中'
    });
  },

  /**
   * 回复评论
   */
  onReplyComment(e) {
    if (!authUtils.isLoggedIn()) {
      authUtils.redirectToLogin();
      return;
    }

    const commentId = e.currentTarget.dataset.commentId;
    const comment = this.data.comments.find(c => c.id === commentId);
    
    this.setData({
      replyTarget: comment ? comment.user.nickname : '',
      replyCommentId: commentId,
      commentContent: ''
    });
  },

  /**
   * 评论输入
   */
  onCommentInput(e) {
    const value = e.detail.value;
    console.log('章节评论输入:', value);
    this.setData({
      commentContent: value
    });
    console.log('章节评论内容已更新:', this.data.commentContent);
  },

  /**
   * 提交评论
   */
  async onSubmitComment() {
    console.log('点击章节发送按钮');
    if (!authUtils.isLoggedIn()) {
      authUtils.redirectToLogin();
      return;
    }

    const { commentContent, replyCommentId, chapterId } = this.data;
    console.log('章节评论提交参数:', { commentContent, replyCommentId, chapterId });
    
    if (!commentContent.trim()) {
      Message.warning({
        context: this,
        content: '请输入评论内容'
      });
      return;
    }

    try {
      const commentData = {
        content: commentContent.trim(),
        parentId: replyCommentId || null
      };

      console.log('章节评论数据:', commentData);

      if (replyCommentId) {
        // 回复评论
        console.log('回复章节评论:', replyCommentId);
        await interactionAPI.replyComment(replyCommentId, commentData);
      } else {
        // 直接评论
        console.log('直接评论章节:', chapterId, '目标类型:', interactionAPI.TARGET_TYPES.CHAPTER);
        await interactionAPI.addComment(interactionAPI.TARGET_TYPES.CHAPTER, chapterId, commentData);
      }

      Message.success({
        context: this,
        content: '评论成功'
      });

      // 清空输入框和回复状态
      this.setData({
        commentContent: '',
        replyTarget: '',
        replyCommentId: ''
      });

      // 刷新评论列表
      this.loadComments();
    } catch (error) {
      console.error('章节评论失败:', error);
      Message.error({
        context: this,
        content: error.message || '评论失败，请重试'
      });
    }
  },

  /**
   * 加载评论列表
   */
  async loadComments() {
    try {
      console.log('加载章节评论:', { chapterId: this.data.chapterId, targetType: interactionAPI.TARGET_TYPES.CHAPTER });
      
      const response = await interactionAPI.getComments(
        interactionAPI.TARGET_TYPES.CHAPTER,
        this.data.chapterId,
        {
          page: 1,
          pageSize: this.data.commentsPagination.pageSize
        }
      );

      console.log('章节评论API响应:', response);

      if (response.code === 200) {
        const commentsData = response.data;
        console.log('章节评论数据:', commentsData);
        
        this.setData({ 
          comments: commentsData.list || [],
          'commentsPagination.hasMore': commentsData.hasMore || false
        });
      }
    } catch (error) {
      console.error('加载章节评论失败:', error);
    }
  }
});
